import React from 'react';
import PropTypes from 'prop-types';
import { Form, Icon, Input, Button, Checkbox, message } from 'antd';
import BrowserHistory from '@/util/history';
import './login.less';

const FormItem = Form.Item;

class Login extends React.Component {
	constructor(props) {
		super(props);
	}
	handleSubmit = (e) => {
		e.preventDefault();
		this.props.form.validateFields((err, values) => {
		  if (!err) {
				AJAX({
					method: 'post',
					url: '/login',
					data: {}
				}).then(res => {
					if (res.errNo === 0) {
						message.success('恭喜您，登陆成功！');
						STORAGE.setItem('access-token', res.data);
						BrowserHistory.push('/app'); // 登陆成功，跳到首页，应该跳到过来的页面（后期优化）
					}
				}).catch(err => message.error(err.errMsg || '请求错误'));
		  } else {
				message.warning('参数错误！');
		  }
		});
	}

	render() {
		const { getFieldDecorator } = this.props.form;
		return (
			<div>
				<div className="login-container">
					<Form onSubmit={this.handleSubmit} className="login-form">
						<h2>BLOG-admin</h2>
						<FormItem>
							{getFieldDecorator('userName', {
								rules: [{ required: true, message: '请填写用户名!' }],
							})(
								<Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="用户名" />
							)}
						</FormItem>
						
						<FormItem>
							{getFieldDecorator('password', {
								rules: [{ required: true, message: '请填写密码!' }],
							})(
								<Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="密码" />
							)}
						</FormItem>

						<FormItem className="mb-0">
							{getFieldDecorator('remember', {
								valuePropName: 'checked',
								initialValue: true,
							})(
								<Checkbox>Remember me</Checkbox>
							)}
							<Button type="primary" htmlType="submit" className="login-form-button">登录</Button>
						</FormItem>
					</Form>
				</div>
			</div>
		);
	}
}
export default Form.create()(Login);
